<template>
  <div>
    <div class="hender" v-if="false">
      <div class="left" style="display: flex" >
        <!-- <img
          src="../../../assets/logo.png"
          height="35px"
          width="70px"
          style="margin: 0 10px 0 20px; margin-top: 12px"
        /> -->
        <div style="color: #333; font-size: 20px; font-weight: 600">
          AI仿生助理
        </div>
      </div>
      <!-- <div
        class="right"
        style="margin-right: 30px; font-size: 16px; color: #666"
      >
        <a-button plain size="small" @click="handleDialog"
          ><i class="el-icon-edit"></i> 更新日志</a-button
        >
      </div> -->
    </div>
    <div class="chat-container">
      <a-card class="box-card" :body-style="{ height: '80vh' }" hoverable >
        <div ref="chatContainer" class="chat-messages">
          <div
            v-for="message in messages"
            :key="message.id"
            class="message"
            :class="{ 'from-me': message.fromMe }"
          >
            <div class="avatar" v-if="!message.fromMe"></div>
            <div class="avatar1" v-else>
              {{ message.from }}
            </div>
            <div class="content" :class="{ content1: !message.fromMe }">
              <!-- {{ message.content }} -->
              <div
                class="main" 
                style="padding-left: 10px"
              >   
                <vue-markdown  :source="message.content"  :breaks="true" :typographer="true" :linkify="true" :highlight="false"></vue-markdown>  
               <div> 
                <div @click="openBig" v-if="!message.fromMe && message.type ==2">
                 <pie title="" height="200"  :key="new Date().getTime()"/>  
                 </div>
              </div>
              </div> 
            </div>
          </div>
        </div>
        <div class="chat-input">
          <a-input
            type="textarea" :autosize="{minRows: 4,maxRows: 8}" 
            v-model="newMessage"
            @keyup.enter.native="sendMessage"
            placeholder="请输入...(发送 1 返回表格， 2 返回图表)"
            style="margin-right: 10px"
          />  
          <a-button type="primary" @click="sendMessage"  size="large">发 送</a-button> 
        </div>
      </a-card> 
    </div>
    <a-modal title="2231 槽展示图" :visible.sync="dialogVisible">
      <div>
       <pie title="" height="400"  :key="new Date().getTime()"/>  
      </div>
      <span slot="footer" class="dialog-footer">
        <a-button type="primary" @click="dialogVisible = false"
          >确 定</a-button>
      </span>
    </a-modal>
  </div>
</template>

<script>
// import MarkdownIt from "markdown-it";
import VueMarkdown from 'vue-markdown';
import Pie from '@/components/chart/Pie'
export default {
  components: {
    VueMarkdown,
    Pie
  },
  data() {
    return {
      dialogVisible: false,
      baseURL: "http://120.77.211.116:8889",
      messages: [
        {
          id: 1,
          from: "You",
          content: "您好，有什么需要我帮助的吗？",
          fromMe: false,
          type:0
        },
      ],
      newMessage: "",
      resultMessage: "",
      newCode: "",
      access_token: "",
      accessCodeInput: "",
      dayLog: [],
      ask:''
    };
  },
  created() { 
    this.checkAccessCode();
    // 添加会话检测，防止因为服务端数据库改变会话id丢失程序报错
    if (localStorage.getItem("idCard")) {
      this.$http
        .get(this.baseURL + "/check/" + localStorage.getItem("idCard"))
        .then((res) => {
          if (res.data.msg === "会话存在") {
            console.log("会话存在");
            this.newCode = localStorage.getItem("idCard");
          } else {
            console.log("会话不存在");
            this.createChat();
          }
        })
        .catch(() => {
          console.log("会话不存在");
          this.createChat();
        });
    } else {
      this.createChat();
    }
  },
  methods: {
      openBig(){
      this.dialogVisible= true;
    },
    // 新建会话ID
    createChat() {
      this.$http.get(this.baseURL + "/chat/new").then((res) => {
        localStorage.setItem("idCard", res.data.conversation_id);
        this.newCode = res.data.conversation_id;
      });
    },
    // 检查访问密码
    checkAccessCode() {
      if (localStorage.getItem("access_code")) {
        this.access_token = localStorage.getItem("access_code");
        return; // 如果本地存储中有 access_code，则直接使用
      }
      // 如果本地存储中没有 access_code，则弹出对话框让用户输入密码
    //   this.$prompt("请输入访问密码", "密码验证", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     inputPattern: /^\S+$/, // 输入不能为空格的密码
    //     inputErrorMessage: "密码不能为空格",
    //   })
    //     .then(({ value }) => {
          this.accessCodeInput = 'arc123456'; // 保存用户输入的密码

          // 发送密码到后端进行验证
          this.$http
            .post(this.baseURL + "/verify", {
              password: this.accessCodeInput,
            })
            .then((res) => { 
              console.log("verify:",JSON.stringify(res));
              if (res.msg === "验证成功") {
                //this.$message.success("验证成功");
                // 验证成功，保存 access_code 到本地存储
                localStorage.setItem("access_code", this.accessCodeInput);
                this.access_token = this.accessCodeInput;
              } else {
                // 验证失败，递归调用 checkAccessCode 继续弹出密码输入框
                this.$message.error("密码错误，请重新输入");
               // this.checkAccessCode();
              }
            })
            .catch(() => {
              // 如果验证出现错误，也可以递归调用 checkAccessCode 继续弹出密码输入框
              // this.checkAccessCode();
            });
        // })
        // .catch(() => {
        //   // 用户点击取消按钮或者关闭对话框时也可以递归调用 checkAccessCode 继续弹出密码输入框
        //   this.checkAccessCode();
        // });
    },

    sendMessage() {
      if (!this.newMessage.trim()) {
        return;
      }
      const newId = this.messages.length + 1;
      var showType = 0 ;
      this.messages.push({
        id: newId,
        from: "Me",
        content: this.newMessage,
        fromMe: true,
        type:showType,
      });
      this.newMessage = "";
      this.ask = this.messages[this.messages.length - 1].content;
      const newResultId = newId + 1;
      var result ='';
      switch (this.ask) {
        case '1':
          result = "出铝量统计<table><tr><td>槽号</td><td>出铝量</td></tr><tr><td>2231</td><td>1</td></tr></table>";    
          showType =1;
          break;
        case '2':
          result = "<div style='width:300px;'>2231 槽展示图<div>";    
          showType =2;
          break; 
        default:
          showType = 0 ;
          result ="展示的内容";
          break;
      }

      this.messages.push({
        id: newResultId,
        from: "You",
        content: "努力思索中，请耐心等待...",
        fromMe: false,
        type: showType
      });
      //聊天框滚动效果
      const chatContainer = this.$refs.chatContainer;
      this.$nextTick(() => {
        chatContainer.scrollTop = chatContainer.scrollHeight;
      });
     
 
      this.messages[newId].content = result
       ///md.render(res.data.data.result);
          //console.log(md.render(res.data.result));
      this.$nextTick(() => {
            chatContainer.scrollTop = chatContainer.scrollHeight;
          });
return
      this.$http
        .post(this.baseURL + "/chat/" + this.newCode, {
          role: "user",
          question: ask,
          access_token: this.access_token,
        })
        .then((res) => {
          if (res.data.result === "访问密码错误,请重新输入") {
            this.messages[newId].content = "访问密码错误,请重新输入";
            return;
          }
         // const md = new MarkdownIt();
          this.messages[newId].content = res.data.result ///md.render(res.data.data.result);
          //console.log(md.render(res.data.result));
          this.$nextTick(() => {
            chatContainer.scrollTop = chatContainer.scrollHeight;
          });
        });
    },
    // 打开更新日志
    handleDialog() { 
      this.dialogVisible = true;
      this.$http.get(this.baseURL + "/log").then((res) => {
        this.dayLog = res.data;
      });
    },
  },
};
</script>

<style scoped lang="less">
/deep/.el-dialog {
  width: 60%;
}
@media screen and (max-width: 700px) {
  /deep/.el-dialog {
    width: 80%;
  }
}
.chat-container {
  box-sizing: border-box;
  height: 80vh;
  width: 100%;
  padding: 20px;
}
.hender {
  line-height: 60px;
  display: flex;
  padding: 10px;
  background-color: #fff;
  border-bottom: 1px solid #ddd;
  vertical-align: bottom;
  align-items: center;
  justify-content: space-between;
}
.chat-messages {
  height: 80%;
  overflow-y: auto;
  border-bottom: 1px solid #ddd;
}

.message {
  display: flex;
  align-items: center;
  margin: 10px;
}

.from-me {
  flex-direction: row-reverse;
}

.avatar {
  min-width: 40px;
  height: 40px;
  background-color: #ccc;
  background-image: url("../../../assets/logo.png");
  background-repeat: repeat-x;
  background-size: cover;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: #fff;
}
.avatar1 {
  min-width: 40px;
  height: 40px;
  background-color: #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: #fff;
}

.content {
  font-size: 16px;
  margin: 10px;
  padding: 15px;
  border-radius: 5px;
  background-color: #d2f9d1;
  text-align: left;
}
.content1 {
  background-color: #f4f6f8;
  font-size: 14px;
}
.main {
  /deep/table {
    border-collapse: collapse;
    margin: 10px;
  }
  /deep/th,
  /deep/td {
    border: 1px solid #ccc;
    padding: 10px;
    text-align: center;
  }
}
.chat-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
}
</style>